package com.nixsolutions.validator;

import com.nixsolutions.bean.User;
import com.nixsolutions.form.UserForm;
import java.sql.Date;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 *
 * @author yakimovich
 */
@Component
public class UserValidator implements Validator {

    public static final String RECAPTCHA_PRIVATE_KEY = "6Ler_-USAAAAAG9oZEqthJd4tgiTVTrmaD_fd-XG";

    @Override
    public boolean supports(Class<?> aClass) {
        return User.class.isAssignableFrom(aClass);
    }

    @Override
    public void validate(Object target, Errors errors) {
        UserForm userForm = (UserForm) target;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login",
                "login.empty", "Login must not be empty.");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
                "password.empty", "Password must not be empty.");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email",
                "email.empty", "Email must not be empty.");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName",
                "firstName.empty", "First name must not be empty.");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName",
                "lastName.empty", "Last name must not be empty.");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthday",
                "birthday.empty", "Birthday must not be empty.");

        if (!(userForm.getPassword())
                .equals(userForm.getPasswordConfirm())) {
            errors.rejectValue("passwordConfirm",
                    "passwordConfirm.passwordDontMatch",
                    "Passwords don't match.");
        }

        if (!isValidEmail(userForm.getEmail())) {
            errors.rejectValue("email", "email.notValid",
                    "Email address is not valid.");
        }

        try {
            Date birthday = Date.valueOf(userForm.getBirthday());
        } catch (IllegalArgumentException e) {
            errors.rejectValue("birthday", "birthday.notValid",
                    "Birthday format must be 'yyyy-MM-dd'.");
        }
    }

    public static boolean isValidEmail(String email) {

        boolean result = true;
        try {
            InternetAddress emailAddr = new InternetAddress(email);
            emailAddr.validate();
        } catch (AddressException ex) {
            result = false;
        }
        return result;
    }

    public boolean reCaptchaValidation(HttpServletRequest req,
            String challenge, String response) {

        String remoteAddr = req.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey(RECAPTCHA_PRIVATE_KEY);

        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(
                remoteAddr, challenge, response);

        return reCaptchaResponse.isValid();
    }
}
